package com.hualan.service.community;

import com.alibaba.fastjson.JSON;
import com.hualan.entity.Result;
import com.hualan.entity.ResultDate;
import com.hualan.entity.Shop;
import com.hualan.utils.EntityFactory;
import com.hualan.utils.ExecUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = {"/panghudaojiaBackend/associatedStores/associatedStoresList","/panghudaojiaBackend/associatedStores/findShopListByAdd","/panghudaojiaBackend/associatedStores/addAssociatedStores"})
public class CommunityShopService extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String location = req.getServletPath();
        if(location.equals("/panghudaojiaBackend/associatedStores/associatedStoresList")){
            String sql = "select shop_id from a_community_shop where community_id = ?";
            List<Object> list = new ArrayList<>();
            list.add(req.getParameter("communityId"));
            List<Integer> shopIds = new ArrayList<>();
            shopIds.add(-1);
            ResultSet resultSet = (ResultSet) ExecUtil.execute(sql,list,req,false);
            try{
                while (resultSet.next()){
                    Integer shopId = resultSet.getInt("shop_id");
                    shopIds.add(shopId);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            ExecUtil.commit();
            ExecUtil.close();
//            System.out.println(shopIds);
            list.clear();
            sql = "select * from a_shop where shopId in "+shopIds.toString()+" and ";
            sql = sql.replace("[","(");
            sql = sql.replace("]",")");
//            System.out.println(sql);
            if(!req.getParameter("shopName").equals("")){
                sql += "shopName like ? and ";
                list.add("%"+req.getParameter("shopName")+"%");
            }
            sql += "\'a\'=\'a\' ";
            System.out.println(sql);
            Integer total = 0;
            ResultSet resultSet2 = (ResultSet) ExecUtil.execute(sql,list,req,false);
            try{
                while (resultSet2.next()){
                    total++;
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            ExecUtil.commit();
            ExecUtil.close();
            Integer pageNum = Integer.parseInt(req.getParameter("pageNum"));
            Integer pageSize = Integer.parseInt(req.getParameter("pageSize"));
            Integer start = pageSize*(pageNum-1);
            Integer end = pageSize*pageNum;
            sql += "limit "+start+","+end;
            ResultSet resultSet1 = (ResultSet) ExecUtil.execute(sql,list,req,false);
            List<Object> shops = new ArrayList<>();
            try{
                while (resultSet1.next()){
                    EntityFactory entityFactory = new EntityFactory(Shop.class);
                    Shop shop = (Shop) entityFactory.startCombine(resultSet1);
                    shops.add(shop);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            ExecUtil.commit();
            ExecUtil.close();
            resp.getWriter().write(JSON.toJSONString(new Result(200,new ResultDate(pageNum,pageSize,total,total/pageSize+(total%pageSize == 0?0:1),shops))));
        }else if(location.equals("/panghudaojiaBackend/associatedStores/findShopListByAdd")){
            String sql = "select shop_id from a_community_shop where community_id = ?";
            List<Object> list = new ArrayList<>();
            list.add(req.getParameter("communityId"));
            List<Integer> shopIds = new ArrayList<>();
            shopIds.add(-1);
            ResultSet resultSet = (ResultSet) ExecUtil.execute(sql,list,req,false);
            try{
                while (resultSet.next()){
                    Integer shopId = resultSet.getInt("shop_id");
                    shopIds.add(shopId);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            ExecUtil.commit();
            ExecUtil.close();
//            System.out.println(shopIds);
            list.clear();
            sql = "select * from a_shop where shopId not in "+shopIds.toString()+" and ";
            sql = sql.replace("[","(");
            sql = sql.replace("]",")");
//            System.out.println(sql);
            if(!req.getParameter("shopName").equals("")){
                sql += "shopName like ? and ";
                list.add("%"+req.getParameter("shopName")+"%");
            }
            sql += "\'a\'=\'a\' ";
            System.out.println(sql);
            Integer total = 0;
            ResultSet resultSet2 = (ResultSet) ExecUtil.execute(sql,list,req,false);
            try{
                while (resultSet2.next()){
                    total++;
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            ExecUtil.commit();
            ExecUtil.close();
            Integer pageNum = Integer.parseInt(req.getParameter("pageNum"));
            Integer pageSize = Integer.parseInt(req.getParameter("pageSize"));
            Integer start = pageSize*(pageNum-1);
            Integer end = pageSize*pageNum;
            sql += "limit "+start+","+end;
            ResultSet resultSet1 = (ResultSet) ExecUtil.execute(sql,list,req,false);
            List<Object> shops = new ArrayList<>();
            try{
                while (resultSet1.next()){
                    EntityFactory entityFactory = new EntityFactory(Shop.class);
                    Shop shop = (Shop) entityFactory.startCombine(resultSet1);
                    shops.add(shop);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            ExecUtil.commit();
            ExecUtil.close();
            resp.getWriter().write(JSON.toJSONString(new Result(200,new ResultDate(pageNum,pageSize,total,total/pageSize+(total%pageSize == 0?0:1),shops))));
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String location = req.getServletPath();
        if(location.equals("/panghudaojiaBackend/associatedStores/addAssociatedStores")){
            String fendeShopCommunityList = req.getParameter("fendeShopCommunityList");
            String[] fendeShopCommunityLists = fendeShopCommunityList.split(",");
            Integer panghuCommunityId =Integer.parseInt(req.getParameter("panghuCommunityId"));
            for(String shopId:fendeShopCommunityLists){
                try{
                    String sql = "insert into a_community_shop values(?,?)";
                    List<Object> list = new ArrayList<>();
                    list.add(panghuCommunityId);
                    list.add(Integer.parseInt(shopId));
                    ExecUtil.execute(sql,list,req,true);
                    ExecUtil.commit();
                    ExecUtil.close();
                }catch (Exception e){
                    resp.getWriter().write(JSON.toJSONString(new Result(500,"该门店已经是该小区的关联门店，无法添加！")));
                }

            }
            String sql = "update community set communityShopCount = (select count(shop_id) from a_community_shop where community_id = ?) where communityId = ?";
            List<Object> list = new ArrayList<>();
            list.add(req.getParameter("panghuCommunityId"));
            list.add(req.getParameter("panghuCommunityId"));
            ExecUtil.execute(sql,list,req,true);
            ExecUtil.commit();
            ExecUtil.close();
            resp.getWriter().write(JSON.toJSONString(new Result(200,"增加成功！")));
        }
    }
}
